package com.gxa.user.redis.timedtask;/**
 * @author JunYu
 * @create 2022-10-08--13:30
 */

import com.gxa.api.shop.ShopApi;
import com.gxa.api.shop.entity.GoodIdAndNum;
import com.gxa.user.redis.utils.RedisLockUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: take-out-project
 *
 * @description: 用于定时更新商品数量
 *
 * @author: JunYu
 *
 * @create: 2022-10-08 13:30
 **/
//@Configuration
@EnableScheduling
public class GoodNumUpdate {
    @Autowired
    ShopApi shopApi;
    @Autowired
    RedisLockUtils redisLockUtils;
    @Scheduled(cron = "0/5 * * * * ?")
    public void updateGoodNum(){
        RedisTemplate redisTemplate = redisLockUtils.getRedisTemplate();
        List<GoodIdAndNum> goodIdAndNumList = shopApi.findGoodIdAndNum();
        Map<String,String> map = new HashMap<>();
        for(GoodIdAndNum goodIdAndNum :goodIdAndNumList)
        {
           map.put(goodIdAndNum.getGoodId().toString(),goodIdAndNum.getNum().toString());
        }
        //获取锁
        if(redisLockUtils.getLock("OpsGoodIdAndNum","Free"))
        {
            redisTemplate.opsForHash().putAll("GoodIdAndNum",map);
            //释放锁
            redisLockUtils.releaseLock("OpsGoodIdAndNum","Free");
        }
    }
    public Integer updateGoodNumByGoodId(Long goodId){
        RedisTemplate redisTemplate = redisLockUtils.getRedisTemplate();
        Integer amountInDB= shopApi.findNumByGoodId(goodId);
        //获取锁
        if(redisLockUtils.getLock("OpsGoodIdAndNum","Free")){
            redisTemplate.opsForHash().put("GoodIdAndNum",goodId,amountInDB);
            //释放锁
            redisLockUtils.releaseLock("OpsGoodIdAndNum","Free");
        }
        return amountInDB;
    }
}
